package com.product.magina.webserviceclient.wsClient;

import com.product.magina.webserviceclient.service.UserInfo;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import java.util.ArrayList;
import java.util.List;

/**
 *  CXF整合webService基本用法
 *  @author：anti_magina
 *  @date：2019-03-29 16:49:26
 */
public class WS_CXF_Basic_V2_Client {

    private static String WSDL_URL = "http://localhost:8081/services/TestService?wsdl";

    public static void main(String[] args) {
        System.out.println("=======================test_String_param========================");
        Object[] plainResult = callService(WSDL_URL, "getUserName", "magina");
        System.out.println("plain result:"+plainResult[0]);
        System.out.println("=======================test_object_param=========================");
        //关键点:UserInfo的package:package com.product.magina.webserviceclient.service.UserInfo
        //保持和服务端package的nameSpace一致.不然会class转换异常
        UserInfo userInfo= new UserInfo();
        userInfo.setUserName("张三");
        userInfo.setAge(12);
        Object[] objectResult = callService(WSDL_URL, "getUser", userInfo);
        UserInfo user = (UserInfo)objectResult[0];
        System.out.println("object result:"+user.getUserName()+"/"+user.getAge());
        System.out.println("========================test_list_param==========================");
        List<UserInfo> list = new ArrayList<UserInfo>();
        UserInfo userInfo1= new UserInfo();
        userInfo1.setUserName("张三1");
        userInfo1.setAge(123);
        list.add(userInfo);
        list.add(userInfo1);
        Object[] listResult = callService(WSDL_URL, "getUserList", list);
        List<UserInfo> userList = (List) listResult[0];
        for(UserInfo p : userList){
            System.out.println("list result:"+p.getUserName()+"/"+p.getAge());
        }
    }

    public static Object[] callService(String wsUrl, String method, Object...arg) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(wsUrl);
        Object[] res = null;
        try {
            res = client.invoke(method, arg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}